package com.huika.renrench.control.investment.activity;

import java.math.BigDecimal;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Intent;
import android.renderscript.Double2;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.android.volley.Response.Listener;
import com.google.gson.reflect.TypeToken;
import com.hk.app.android.lib.encrypt.MD5Security;
import com.huika.lib.ui.widget.ToastMsg;
import com.huika.lib.ui.widget.dialog.MMAlert;
import com.huika.lib.utils.MoneyShowTool;
import com.huika.renrench.GlobalApp;
import com.huika.renrench.R;
import com.huika.renrench.config.UrlConstants;
import com.huika.renrench.control.common.base.BaseAct;
import com.huika.renrench.control.my.activity.RechargeActivity;
import com.huika.renrench.http.FormResultRequest;
import com.huika.renrench.http.JSONWrapAjaxParams;
import com.huika.renrench.http.RequestResult;
import com.huika.renrench.http.ServerJsonUnParseError;
import com.huika.renrench.support.bean.AccountPropertyBean;
import com.huika.renrench.support.bean.UserModel;
import com.huika.renrench.view.TitleBarHelper;

/**
 * 
 * @description：立即投资
 * @author zc
 * @date 2015年6月2日 上午9:50:12
 */
public class ImmediatelyInvestActivity extends BaseAct implements Listener<RequestResult<HashMap<String, String>>> {

	private TextView balance_detail;
	private TextView use_balance_detail;
	private EditText invest_money_detail;
	private EditText pay_password_detail;
	private Button confirm_invest;
	private String investBalance;
	private String userId;
	private double balance;
	private String startInvest;//起投额 
	
	@Override
	public void setRootView() {
		setContentView(R.layout.activity_investment);
	}
	
	@Override
	protected void initData() {
		super.initData();
		TitleBarHelper barHelper = new TitleBarHelper(this, -1);
		barHelper.setTitleMsg("立即投资");
		barHelper.setLeftMsg("投资");
		investBalance = getIntent().getStringExtra("investBalance");
		startInvest = getIntent().getStringExtra("startInvest");
		userId = GlobalApp.userModel.getUserId();
		balance = GlobalApp.userModel.getBalance();
	}
	
	private void addInvest(String userId, String investAmount, String payPwd, int dev) {
		showLoadingDialog(getString(R.string.common_loading));
		JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
		ajaxParams.putCommonTypeParam("userId", userId);
		ajaxParams.putCommonTypeParam("investAmount", investAmount);
		ajaxParams.putCommonTypeParam("payPwd", MD5Security.getMd5_32(payPwd).toUpperCase());
		ajaxParams.putCommonTypeParam("dev", 2);
		FormResultRequest<HashMap<String, String>> request = new FormResultRequest<HashMap<String, String>>(UrlConstants.ADDINVEST, this, this, new TypeToken<RequestResult<HashMap<String, String>>>() {
		}.getType());
		request.setRequestParams(ajaxParams);
		executeRequest(request);
	}
	
	@Override
	protected void initWidget() {
		super.initWidget();
		balance_detail = (TextView) findViewById(R.id.balance_detail);
		use_balance_detail = (TextView) findViewById(R.id.use_balance_detail);
		invest_money_detail = (EditText) findViewById(R.id.invest_money_detail);
		pay_password_detail = (EditText) findViewById(R.id.pay_password_detail);
		confirm_invest = (Button) findViewById(R.id.confirm_invest);
		confirm_invest.setOnClickListener(this);
		
		balance_detail.setText(MoneyShowTool.twolastDF(Double.parseDouble(investBalance)) + "元");
		use_balance_detail.setText(MoneyShowTool.twolastDF(balance) + "元");
		
		invest_money_detail.addTextChangedListener(new MyWatcher());
//		getDataFromNet(userId);
		executeUpdateUserInfoList();
		
	}
	
	class MyWatcher implements TextWatcher {
		String tempStr;
		
		@Override
		public void afterTextChanged(Editable s) {
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			tempStr = s.toString();
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			if(!checkInputMoney(s.toString())) {
				invest_money_detail.setText(tempStr);
				invest_money_detail.setSelection(invest_money_detail.length());
				return;
			} else if(s.length() > 1 && s.toString().substring(0, 1).equals("0") && !s.toString().startsWith("0.")) {
				invest_money_detail.setText(s.toString().substring(1));
				invest_money_detail.setSelection(invest_money_detail.length());
			}
		}
		
	}
	
	private boolean checkInputMoney(String money) {
		String patten = "^[0-9]{0,9}+(([.]{1})+([0-9]{0,2}))?$";
		return (money.equals("") || money.equals(".") || money.equals("0."))?true:money.matches(patten);
	}
	/**
	 * 
	 * @description：判断是否可以提交的金额
	 * @author zc
	 * @date 2015年6月23日 下午3:11:14
	 */
	private boolean canSubmitMoney(String money) {
		String patten = "^[0-9]+(.[0-9]{1,2})?$";
		return money.matches(patten);
	}
	
	@Override
	protected void onRestart() {
		super.onRestart();
//		getDataFromNet(userId);
		executeUpdateUserInfoList();
	}
	
	/** 获取网络数据,刷新用户信息*/
	private void executeUpdateUserInfoList(){
		JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
		ajaxParams.putCommonTypeParam("userId", GlobalApp.getInstance().getUserId());//userId
		FormResultRequest<UserModel> request = new FormResultRequest<UserModel>(UrlConstants.FINDUSERBYUSERID, getUpdateUserResp, this, new TypeToken<RequestResult<UserModel>>() {}.getType());
		request.setRequestParams(ajaxParams);
		executeRequest(request);
	}
	
	private Listener<RequestResult<UserModel>> getUpdateUserResp=new Listener<RequestResult<UserModel>>() {
		
		@Override
		public void onResponse(RequestResult<UserModel> result) {
			
			dismissLoadingDialog();
			if (result.flag == 1) {
				if (result != null && result.getRs() != null) {
					balance = result.getRs().getBalance();
					GlobalApp.userModel.setBalance(balance);
					use_balance_detail.setText(MoneyShowTool.twolastDF(result.getRs().getBalance()) + "元");
				}
			} else {
//				showToastMsg(result.msg);
			}
		}
	};
	
	@Override
	public void widgetClick(View v) {
		super.widgetClick(v);
		switch (v.getId()) {
			case R.id.confirm_invest:
				check();
				break;

			default:
				break;
		}
	}
	
	private void check() {
		if(invest_money_detail.length() == 0) {
			ToastMsg.showToastMsg(this, "投资金额不能小于起投金额" + startInvest + "元");
			return ;
		} else if(!canSubmitMoney(invest_money_detail.getText().toString())) {
			ToastMsg.showToastMsg(this, "您输入的格式不正确，请重新输入");
			invest_money_detail.setText("");
			return;
		}
		else if(pay_password_detail.length() == 0) {
			ToastMsg.showToastMsg(this, "请输入交易密码");
			return;
		} 
		else if(Double.parseDouble(invest_money_detail.getText().toString()) > balance) {
			warning();
			return;
		} else {
			addInvest(userId, invest_money_detail.getText().toString(), pay_password_detail.getText().toString(), 2);
		}
	}

	private Dialog dialog ;
	
	private void warning() {
		dialog = MMAlert.createShowCenterDialog(context, "温馨提示", "您的余额不足，请前往账户中心进行充值。", "忽略", "前往充值", null, new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showActivity(ImmediatelyInvestActivity.this, RechargeActivity.class);
			}
		});
		dialog.show();
	}
	
	Intent intent = null;
	
	@Override
	public void onErrorResponse(VolleyError error) {
		super.onErrorResponse(error);
		try {
			if(error instanceof ServerJsonUnParseError) {
				String res = ((ServerJsonUnParseError) error).result;
				JSONObject jsonObject = new JSONObject(res);
				if(jsonObject.getInt("flag") == 0) {
					pay_password_detail.setText("");
				}
			}
		}
		catch (JSONException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onResponse(RequestResult<HashMap<String, String>> arg0) {
		if(arg0.flag == 1) {
			intent = new Intent(this, InvestResultActivity.class);
			intent.putExtra("money", arg0.getRs().get("investAmount"));
			intent.putExtra("time", arg0.getRs().get("createTime"));
//			getDataFromNet(userId);
			executeUpdateUserInfoList();
			startActivity(intent);
			finish();
		} else {
			pay_password_detail.setText("");
		}
//		ToastMsg.showToastMsg(this, arg0.msg);
	}
	
	private void getDataFromNet(String userId) {
		showLoadingDialog(getString(R.string.common_loading));
		JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
		ajaxParams.putCommonTypeParam("userId", userId);
		FormResultRequest<AccountPropertyBean> getResultRequest = new FormResultRequest<AccountPropertyBean>(
				UrlConstants.GETUSERTOTALAMOUNT, new Listener<RequestResult<AccountPropertyBean>>() {

					@Override
					public void onResponse(RequestResult<AccountPropertyBean> arg0) {
						dismissLoadingDialog();
						if(arg0.flag == 1) {
							double total = GlobalApp.getInstance().getUseBalance(arg0.getRs().rechargeAmount, 
									arg0.getRs().withdrawAmount, arg0.getRs().investRevenue, 
									arg0.getRs().frozenBalance, arg0.getRs().investAmount, arg0.getRs().revenueFeeAmount);
							use_balance_detail.setText(MoneyShowTool.twolastDF(total) + "元");
							balance = Double.parseDouble(use_balance_detail.getText().toString().substring(0, use_balance_detail.length() - 1));
							
						}
					}
				}, this,
				new TypeToken<RequestResult<AccountPropertyBean>>() {
				}.getType());
		getResultRequest.setRequestParams(ajaxParams);
		executeRequest(getResultRequest);
	}
}
